package com.example.tms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.tms.bean.DeptInfo;
import com.example.tms.bean.ReturnInfo;
import com.example.tms.mapper.CarMapper;
import com.example.tms.mapper.DeptMapper;
import com.example.tms.mapper.DriverMapper;
import com.example.tms.mapper.UserMapper;
import org.apache.catalina.mapper.Mapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.tms.annotation.*;
import java.util.*;

/**
 * 组织架构
 */
@RestController
public class DeptController {

    private final DeptMapper deptMapper;
    private final CarMapper carMapper;
    private final DriverMapper driverMapper;
    private final UserMapper userMapper;

    @Autowired
    public DeptController(DeptMapper deptMapper, CarMapper carMapper, DriverMapper driverMapper, UserMapper userMapper){
        this.deptMapper = deptMapper;
        this.carMapper = carMapper;
        this.driverMapper = driverMapper;
        this.userMapper = userMapper;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //查询部门信息树结构列表
    @RequiresPermissions("111")
    @RequestMapping(value = "dept/tree", method = RequestMethod.GET)
    public ReturnInfo getDeptInfoTree(){
        List<DeptInfo> root = deptMapper.findByFjdid("-1");//获取根节点（获取的值存到list中）
        JSONArray.parseArray(JSON.toJSONString(buildTree(root)));
        return ReturnInfo.info2(root);
    }

    private List<DeptInfo> buildTree(List<DeptInfo> root){
        for (DeptInfo deptInfo : root) {
            List<DeptInfo> children = deptMapper.findByFjdid(deptInfo.getBumenid()); //查询某节点的子节点（获取的是list）
            buildTree(children);
            deptInfo.setChildren(children);
        }
        return root;
    }

    //查询部门信息树结构列表
    @RequiresPermissions("111")
    @RequestMapping(value = "dept", method = RequestMethod.GET)
    public ReturnInfo getDeptInfoAll(){
        return ReturnInfo.info2(deptMapper.findAll());
    }

    //查询部门信息树结构列表（基础）
    @RequestMapping(value = "deptlist", method = RequestMethod.GET)
    public ReturnInfo getDeptInfoListAll(){
        List<DeptInfo> deptInfos = deptMapper.findAll();
        List<DeptInfo> deptList = new ArrayList<>();
        for(DeptInfo deptInfo : deptInfos){
            deptList.add(new DeptInfo(deptInfo.getBumenid(),deptInfo.getName()));
        }
        return ReturnInfo.info2(deptList);
    }

    //查询部门信息
    @RequiresPermissions("111")
    @RequestMapping(value = "dept/{bumenid}", method = RequestMethod.GET)
    public DeptInfo getDeptInfo(@PathVariable String bumenid){
        DeptInfo deptInfo = deptMapper.findByBumenid(bumenid);
        deptInfo.setSjbm(deptMapper.findByBumenid(deptInfo.getFjdid()).getName());
        return deptInfo;
    }

    //新建部门信息
    @MonitorRequest
    @RequiresPermissions("112")
    @RequestMapping(value = "dept", method = RequestMethod.POST)
    public List<Map<String,Object>> saveDeptinfo(@RequestBody DeptInfo deptInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if (deptInfo.getBumenid().equals("")) {
            map.put("bumenid",  "0");
        }
        if (deptInfo.getName().equals("")) {
            map.put("name", "0");
        }
        if (deptInfo.getFzr().equals("")) {
            map.put("fzr", "0");
        }
        if (deptInfo.getLxfs().equals("") || !checkLxfs(deptInfo.getLxfs())) {
            map.put("lxfs", "0");
        }
        if (deptInfo.getFjdid()==null) {
            map.put("fjdid", "0");
        }
        list.add(map);
        if(map.isEmpty()){
            deptInfo.setSfcz(true);
            deptMapper.save(deptInfo);
            logger.info("新建部门"+deptInfo.toString());
        }
        return list;
    }

    //更新部门信息
    @MonitorRequest
    @RequiresPermissions("113")
    @RequestMapping(value = "dept", method = RequestMethod.PUT)
    public List<Map<String,Object>> updateDeptinfo(@RequestBody DeptInfo deptInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(deptInfo.getBumenid()==null||deptMapper.findByBumenid(deptInfo.getBumenid())==null){
            map.put("bumenid", "1");//部门名称不存在
        }else if(deptInfo.getBumenid().equals("")){
            map.put("bumenid", "0");
        }
        if (deptInfo.getName().equals("")) {
            map.put("name", "0");
        }
        if (deptInfo.getFzr().equals("")) {
            map.put("fzr", "0");
        }
        if (deptInfo.getLxfs().equals("") || !checkLxfs(deptInfo.getLxfs())) {
            map.put("lxfs", "0");
        }
        if (deptInfo.getFjdid()==null) {
            map.put("fjdid", "0");
        }
        list.add(map);
        if(map.isEmpty()){
            deptInfo.setSfcz(true);
            deptMapper.saveAndFlush(deptInfo);
            logger.info("更新部门"+deptInfo.toString());
        }
        return list;
    }

    //删除部门信息（假删除 部门id）
    @MonitorRequest
    @RequiresPermissions("114")
    @RequestMapping(value = "dept/{bumenid}", method = RequestMethod.DELETE)
    public ReturnInfo deleteDeptInfo(@PathVariable String bumenid) {
        String b;
        if(deptMapper.findByBumenid(bumenid)==null){
            b = "删除失败！";
        }else if(!deptMapper.findByFjdidandBumenid(bumenid).isEmpty()){
            b="该部门存在下级部门，不能删除！";
        }else if(!carMapper.findByBumenid(bumenid).isEmpty()){
            b="该部门存在车辆，不能删除！";
        }else if(!driverMapper.findByBumenid(bumenid).isEmpty()){
            b="该部门存在驾驶员，不能删除！";
        }else if(!userMapper.findByBumenid(bumenid).isEmpty()){
            b="该部门存在用户，不能删除！";
        }else{
            deptMapper.deleteByBumenid(bumenid);
            b = "删除成功！";
            logger.info("删除部门"+bumenid);
        }
        return ReturnInfo.info1(b);
    }

    //检查联系方式格式
    private Boolean checkLxfs(String  lxfs){
        Boolean b = false;
        if(lxfs.matches("^\\d+$")){
            b = true;
        }
        return b;
    }
}
